﻿#include "writesession.h"
#include "utils.h"

//#include <netinet/in.h>

#include <QFile>
#include <winsock.h>

namespace TFTP {

WriteSession::~WriteSession()
{
}


void WriteSession::sendAck()
{
    QByteArray dgram;
    dgram.resize(4);

    wordOfArray(dgram)[0] = htons( ACK );
	wordOfArray(dgram)[1] = htons( currentBlock );
	
    if( ti.sd->writeDatagram(dgram.data(), dgram.size(), ti.dAddr, ti.dPort) == -1 ){
        qWarning("发送确认数据包时出错 [%d]", ti.sd->error() );
    }
}


void WriteSession::actualWriteBlock(char *data, uint32_t size)
{
	switch(currentMode)
	{
		case NetAscii:
            qWarning("不支持NetAscii传输");
			break;
		case Octet:
            m_currentFile->write( data, size );
			break;
	}
}


bool WriteSession::parseData(const QByteArray &dgram)
{
	if ( ntohs(wordOfArray(dgram)[0]) != DATA )
	{
        qWarning("未将数据打包传递给parseData（）");
		return true;
	}
	
	if ( currentBlock != ntohs(wordOfArray(dgram)[1]) -1 )
	{
		qWarning("Expected %d, got %d", currentBlock+1, ntohs(wordOfArray(dgram)[1]));
        ti.sendError(IllegalOp, "块序列错误");
		return true;
	}
	
	currentBlock = ntohs(wordOfArray(dgram)[1]);
	
	int length = dgram.size() - 4;
	
    actualWriteBlock( (char*)dgram.data() +4, length );
    sendAck();
	
	if ( length != 512 )
    {
        return true;
    }

	return false;
}

};
